package com.dslcode.cloud.provider.goods.controller;

import com.dslcode.cloud.common.api.goods.GoodsAPI;
import com.dslcode.cloud.common.dto.goods.GoodsBuyDTO;
import com.dslcode.cloud.common.dto.goods.GoodsCommonDetailDTO;
import com.dslcode.cloud.common.dto.goods.GoodsDTO;
import com.dslcode.cloud.common.model.goods.GoodsCommon;
import com.dslcode.cloud.common.utils.AjaxResponse;
import com.dslcode.cloud.provider.goods.service.GoodsCommonService;
import com.dslcode.cloud.provider.goods.service.GoodsService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Set;

/**
 * Created by dongsilin on 2017/9/21.
 */
@Slf4j
@RestController
public class GoodsController implements GoodsAPI{

    @Autowired
    private GoodsCommonService goodsCommonService;
    @Autowired
    private GoodsService goodsService;

    @Override
    public AjaxResponse<PageInfo<GoodsCommon>> list(@RequestParam(name = "pageNum", defaultValue = "1") int pageNum, @RequestParam(name = "pageSize", defaultValue = "10") int pageSize){
        PageHelper.startPage(pageNum, pageSize);
        List<GoodsCommon> goodsCommons = goodsCommonService.findAll();
        return AjaxResponse.buildSuccessData(new PageInfo(goodsCommons));
    }

    @Override
    public AjaxResponse<GoodsCommon> one(@PathVariable(name = "id") Long id){
        return AjaxResponse.buildSuccessData(goodsCommonService.findById(id));
    }

    /**
     * 检查库存
     * @param id
     * @param buyNum
     * @return
     * @throws Exception
     */
    @Override
    public AjaxResponse<GoodsBuyDTO> checkStorage(@PathVariable(name = "id") Long id, @RequestParam int buyNum) throws Exception {
        return AjaxResponse.buildSuccessData(goodsService.checkStorage(id, buyNum));
    }

    /**
     * 扣减库存
     * @param goodsBuyDTOs
     * @return
     * @throws Exception
     */
    @Override
    public AjaxResponse reduceStorage(@RequestBody Set<GoodsBuyDTO> goodsBuyDTOs) {
        try {
            goodsService.reduceStorage(goodsBuyDTOs);
            return AjaxResponse.buildSuccess();
        } catch (Exception e) {
            return AjaxResponse.buildFailed(e.getMessage());
        }
    }

    @Override
    public AjaxResponse<GoodsCommonDetailDTO> detail(@PathVariable(name = "id") Long id){
        GoodsCommonDetailDTO goodsCommonDetailDTO = goodsCommonService.findDetail(id);
        GoodsDTO goodsDTO = goodsService.findDetail(goodsCommonDetailDTO.getGoodses().get(0).getId());
        log.info("goodsDTO = {}", goodsDTO);
        return AjaxResponse.buildSuccessData(goodsCommonDetailDTO);
    }

}
